<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <!-- <el-form-item label="标题">
          <el-input
            v-model="formInline.name"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="是否显示" class="movement">
          <el-select v-model="formInline.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="时间">
          <el-date-picker v-model="formInline.value" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        max-height="600"
        border
        style="width: 100%"
      >
        <!-- <el-table-column
          align="center"
          label="序号"
          width="70"
          type="index"
          :index="indexMethod"
        >
        </el-table-column> -->
        <el-table-column prop="id" align="center" label="ID" width="70">
        </el-table-column>
        <el-table-column prop="pay_big" align="center" label="消费金额">
          <template slot-scope="scope">
            <span>{{ scope.row.pay_small + "-" + scope.row.pay_big }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="percentage" align="center" label="返现百分比">
          <template slot-scope="scope">
            <span>{{ scope.row.percentage + "%" }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="image" align="center" label="项目图片">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="'https://bjsf.bjsky.top' + scope.row.image"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="sort" align="center" label="排序">
        </el-table-column> -->
        <!-- <el-table-column prop="status" align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="2"
              active-text="上架"
              inactive-text="下架"
              @change="ifLook(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!-- <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            > -->
            <el-button type="danger" size="mini" @click="sanChu(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 100, 200, 300]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="45%"
      :before-close="handleClose"
      :title="titleText"
      ref="form"
    >
      <el-form
        :model="formLabelAlign"
        label-width="40px"
        ref="form"
        :rules="rules"
      >
        <!-- <div class="oneLine">
          <el-form-item label="标题" prop="name">
            <el-input
              v-model="formLabelAlign.name"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
        </div> -->
        <div class="oneLine1" v-for="(item, index) in rankingList" :key="index">
          <p>当分享用户</p>
          <el-form-item :label="'消费'">
            <el-input
              class="dialogInput"
              v-model="formLabelAlign.pay_small"
            ></el-input>
            <span>元</span>
          </el-form-item>
          <el-form-item :label="'至'">
            <el-input
              class="dialogInput"
              v-model="formLabelAlign.pay_big"
            ></el-input>
            <span>元时，</span>
          </el-form-item>
          <el-form-item :label="'返现'">
            <el-input
              class="dialogInput"
              v-model="formLabelAlign.percentage"
            ></el-input>
            <span>%</span>
            <!-- <i class="el-icon-plus" @click="addFilterCriteria(item, index)"></i>
            <i
              v-if="index > 0"
              class="el-icon-delete"
              @click.prevent="removeFilterCriteria(index)"
            ></i> -->
          </el-form-item>
        </div>

        <!-- <div class="oneLine">
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="formLabelAlign.sort"
              placeholder="请序号"
            ></el-input>
          </el-form-item>
        </div> -->
        <!-- <div class="oneLine">
          <el-form-item label="项目图片" prop="imageUrl">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFiles"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
              >
                <el-image
                  v-if="imageUrl"
                  class="imageGood"
                  :src="imageUrl"
                  style="width: 360px; height: 180px"
                ></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </div> -->
      </el-form>
      <div class="btnBox">
        <el-button type="primary" dialogVisible class="confirm" @click="save"
          >确 认</el-button
        >
        <el-button
          type="primary"
          dialogVisible
          class="confirm"
          @click="submitData()"
          >返 回</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { opinions, uploadFiles } from "../../../utils/api";
import {
  getShareCashback,
  addShareCashback,
  editKXXM,
  delShareCashback,
} from "../../../utils/main";
export default {
  data() {
    return {
      options: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "2",
          label: "否",
        },
      ],
      formLabelAlign: {
        name: "",
        sort: "",
        avatar: "",
      },
      rankingList: [
        {
          ranking: "",
          cashback: "",
        },
      ],
      fileLimit: 1,
      //   上传图片
      fileList: [],
      headers: { "Content-Type": "multipart/form-data" },
      loading: false,
      token: sessionStorage.getItem("token"),
      dialogVisible: false,
      formInline: {
        status: "",
        name: "",
      },
      tableData: [],
      parameter: {
        common: "",
      },
      total: 0,
      limit: 10,
      page: 1,
      name: "",
      status: "",
      currentPage: 1,
      type: 2,
      imageUrl: "",
      imageUrl1: "",
      titleText: "",
      parent_id: "0",
      status: "",
      value: "",
      imgHeader: this.Global.imgHeader,

      fileType: ["png", "jpg", "jpeg"],
      rules: {
        sort: [
          {
            validator: (rule, value, callback) => {
              var reg = /^(0|[1-9]\d*)$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0的整数"));
              }
              if (value > 999999999) {
                callback(new Error("不能大于999999999"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        pay_small: [
          {
            validator: (rule, value, callback) => {
              var reg = /^\d+(\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0且小数位不超过两位的数字"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        pay_big: [
          {
            validator: (rule, value, callback) => {
              var reg = /^\d+(\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0且小数位不超过两位的数字"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        percentage: [
          {
            validator: (rule, value, callback) => {
              var reg = /^\d+(\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0且小数位不超过两位的数字"));
              } else if (value > 100) {
                callback(new Error("不能大于100"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    addFilterCriteria(item, index) {
      this.rankingList.push({
        ranking: item.ranking,
        cashback: item.cashback,
      });
    },
    removeFilterCriteria(index) {
      this.rankingList.splice(index, 1);
    },
    ifLook(row) {
      // console.log(row.status);
      editKXXM(
        this.token,
        row.parent_id,
        row.name,
        row.sort,
        row.image,
        row.type,
        row.status,
        row.id
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.getList();
        }
      });
    },
    // 返回
    submitData() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    //查询
    onSubmit() {
      // this.opinionsS();
      this.name = this.formInline.name;
      this.status = this.formInline.status;
      this.page = 1;
      this.getList();
    },
    handleReset() {
      this.name = "";
      this.status = "";
      this.formInline.name = "";
      this.formInline.status = "";
      this.getList();
    },
    //序号
    indexMethod(index) {
      if (this.total < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },
    //关闭
    handleClose(done) {
      this.$refs.form.resetFields();
      this.imageUrl = "";
      done();
      // this.$refs[formName].resetFields();
    },
    //条数
    handleSizeChange(val) {
      this.limit = val;
      // this.opinionsS();
      this.getList();
    },
    //页数
    handleCurrentChange(val) {
      this.page = val;
      // this.opinionsS();
      this.getList();
    },
    // 序号排序
    indexMethod(index) {
      if (this.total < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },
    // 新增
    handleAdd() {
      this.formLabelAlign = {};
      this.imageUrl = "";
      this.dialogVisible = true;
      this.titleText = "新增";
    },
    // 编辑
    handleEdit(row) {
      let obj = JSON.parse(JSON.stringify(row));
      this.formLabelAlign = obj;
      this.imageUrl = this.imgHeader + obj.image;
      this.dialogVisible = true;
      this.titleText = "编辑";
      if (obj.status == 1) {
        this.dialogVisible = false;
        this.$message({
          type: "warning",
          message: "显示状态下不能编辑",
        });
      }
    },
    //确定添加
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // console.log(this.formLabelAlign, "8888880");
          if (this.formLabelAlign.id != null) {
            // console.log(this.formLabelAlign, "000");
            // 编辑
            editKXXM(
              this.token,
              this.parent_id,
              this.formLabelAlign.name,
              this.formLabelAlign.sort,
              this.imageUrl1,
              this.formLabelAlign.type,
              this.formLabelAlign.status,
              this.formLabelAlign.id
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "修改成功",
                });
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            // console.log(this.formLabelAlign, "111");

            // 新增
            addShareCashback(
              this.token,
              this.formLabelAlign.pay_small,
              this.formLabelAlign.pay_big,
              this.formLabelAlign.percentage
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "新增成功",
                });
                this.total = res.data.data.count;
                this.formLabelAlign = {};
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 删除
    sanChu(row) {
      if (row.status == 1) {
        this.dialogVisible = false;
        this.$message({
          type: "warning",
          message: "显示状态下不能删除",
        });
        return;
      }
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log(row.id);
          delShareCashback(this.token, row.id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // // 新增
    // handleRemove() {},
    // //超出文件个数的回调
    // handleExceed() {
    //   this.$message({
    //     type: "warning",
    //     message: "超出最大上传文件数量的限制！",
    //   });
    //   return;
    // },
    // //上传文件的格式
    // beforeUpload(file) {
    //   if (file.type != "" || file.type != null || file.type != undefined) {
    //     //截取文件的后缀，判断文件类型
    //     const FileExt = file.name.replace(/.+\./, "").toLowerCase();
    //     //计算文件的大小
    //     const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
    //     //如果大于50M
    //     if (!isLt5M) {
    //       this.$message.error("上传文件大小不能超过 1MB!");
    //       return false;
    //     }
    //     // 如果文件类型不在允许上传的范围内;
    //     if (this.fileType.includes(FileExt)) {
    //       return true;
    //     } else {
    //       this.$message.error("上传文件格式不正确!");
    //       return false;
    //     }
    //   }
    // },
    // //上传成功后的回调
    // handleSuccess(i) {
    //   this.$message({
    //     message: "上传成功",
    //     type: "success",
    //   });
    //   // this.handleClose();
    //   this.fileList.splice(i, 1); //删除上传的文件
    // },
    // //上传文件的事件
    // uploadFiles(item) {
    //   this.$message("文件上传中........");
    //   //上传文件的需要formdata类型;所以要转
    //   uploadFiles(item.file).then((res) => {
    //     if (res.data.status != false || res.data.id != null) {
    //       console.log(res);
    //       res.data.data.saveurl; //半截
    //       res.data.data.weburl; //全拼
    //       this.imageUrl1 = res.data.data.saveurl;
    //       this.imageUrl = res.data.data.weburl;
    //       this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
    //       let i = this.fileList.indexOf(item.file);
    //       this.handleSuccess(i);
    //     }
    //   });
    // },
    // 获取列表
    async getList() {
      this.loading = true;
      let res = await getShareCashback(this.token, this.page, this.limit);
      if (res.data.status) {
        this.tableData = res.data.data.data || [];
        this.total = res.data.data.count;
        // console.log(this.tableData, "55555");
        let timer = setTimeout(() => {
          this.loading = false;
          clearTimeout(timer);
        }, 400);
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/login");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
        let timer = setTimeout(() => {
          this.$message.error(res.data.msg);
        }, 5000);
      }
    },
    //列表数据
    // opinionsS() {
    //   this.loading = true;
    //   opinions(
    //     this.token,
    //     this.page,
    //     this.limit,
    //     this.value,
    //     this.formInline.mobile,
    //     this.formInline.name
    //   )
    //     .then((res) => {
    //       if (res.data.status) {
    //         this.tableData = res.data.data.data;
    //         this.total = res.data.data.count;
    //         this.tableData.forEach((item) => {
    //           if (item.avatar) {
    //             item.image = item.avatar;
    //             item.img = "https://bjsf.bjsky.top" + item.avatar;
    //           }
    //           if (item.ctime) {
    //             item.ctime_text = this.getNowTime(item.ctime * 1000);
    //           }
    //         });
    //         let timer = setTimeout(() => {
    //           this.loading = false;
    //           clearTimeout(timer);
    //         }, 400);
    //       } else {
    //         if (res.data.msg == "token失效,请重新进行登录") {
    //           this.$router.push("/login");
    //         }
    //         if (res.data.msg == "此账号没有权限") {
    //           this.$message.error(res.data.msg);
    //           this.loading = false;
    //         }
    //         let timer = setTimeout(() => {
    //           this.$message.error(res.data.msg);
    //         }, 5000);
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err.message);
    //     });
    // },
    // getNowTime(e) {
    //   let date = new Date(e);
    //   let year = date.getFullYear();
    //   let month = date.getMonth() + 1;
    //   let day = date.getDate();
    //   let hour = date.getHours();
    //   let minute = date.getMinutes();
    //   month = month < 10 ? "0" + month : month;
    //   day = day < 10 ? "0" + day : day;
    //   hour = hour < 10 ? "0" + hour : hour;
    //   minute = minute < 10 ? "0" + minute : minute;
    //   return year + "-" + month + "-" + day + " " + hour + ":" + minute;
    // },
  },
  mounted() {
    // this.opinionsS();
    this.getList();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.divFlex {
  display: flex;
  align-items: center;
}
.oneLine {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
}
.addP {
  font-size: 22px;
  text-align: center;
  margin-bottom: 10px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.btnBox {
  display: flex;
  justify-content: center;
}
.oneLine1 {
  display: flex;
}
.oneLine1 p {
  position: relative;
  top: 10px;
}
.dialogInput {
  width: 80px;
}
.el-icon-delete,
.el-icon-plus {
  margin-left: 15px;
  margin-top: 8px;
  color: rgb(223, 38, 38);
  font-size: 22px;
}
.el-icon-plus {
  color: darkgray;
}
</style>